package com.qiantu.phone.widget;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.hjq.base.BaseAdapter;
import com.hjq.base.DensityUtils;
import com.hjq.shape.drawable.ShapeType;
import com.hjq.shape.layout.ShapeFrameLayout;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.manager.SceneOperateManager;
import com.qiantu.phone.ui.activity.EditSceneActivityNew;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.PanelBindDeviceActivity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.activity.SceneManageActivity;
import com.qiantu.phone.ui.adapter.HomeSceneAdapter;
import com.qiantu.phone.ui.adapter.RoomManagerSceneAdapter;
import com.qiantu.phone.ui.fragment.SceneFragment;
import com.qiantu.phone.utils.SceneDetailUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class HomeTopSceneView extends ShapeFrameLayout {

    private RecyclerView sceneRecyclerView;
//    private RecycleViewIndicator recycleViewIndicator;
    private View btnAddScene;

    private RoomManagerSceneAdapter mHomeSceneAdapter;
    private boolean hasScene;
    /**
     * 0 默认 1常用 2通用
     */
    private int type;
    //场景
//    private List<SceneBean> scenes = null;
    private String roomSerialNo;
    private int marginLeftRight;
    private int shadowSize;
    private Handler mHandler;
    private int marginTop;

    private SceneOperateManager mSceneOperateManager;

    public HomeTopSceneView(Context context, int type, String roomSerialNo) {
        this(context, null, type, roomSerialNo);
    }

    public HomeTopSceneView(Context context, AttributeSet attrs, int type, String roomSerialNo) {
        this(context, attrs, 0, type, roomSerialNo);
    }

    public HomeTopSceneView(Context context, AttributeSet attrs, int defStyleAttr, int type, String roomSerialNo) {
        super(context, attrs, defStyleAttr);
        this.type = type;
        this.roomSerialNo = roomSerialNo;
        StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
        layoutParams.height = 1;
        setLayoutParams(layoutParams);
        marginLeftRight = getResources().getDimensionPixelSize(R.dimen.dp_12);
        int shadowOffsetX = getResources().getDimensionPixelSize(R.dimen.dp_1);
        int shadowOffsetY = getResources().getDimensionPixelSize(R.dimen.dp_1);
        shadowSize = getResources().getDimensionPixelSize(R.dimen.dp_4);
        marginTop = getResources().getDimensionPixelSize(R.dimen.dp_16);
        getShapeDrawableBuilder().setShape(ShapeType.RECTANGLE);
        getShapeDrawableBuilder().setRadius(getResources().getDimensionPixelSize(R.dimen.dp_8));
        getShapeDrawableBuilder().setSolidColor(AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor));
        getShapeDrawableBuilder().setShadowColor(AppApplication.getInstance().getThemeColor(R.attr.shapeShadowColor));
        getShapeDrawableBuilder().setShadowOffsetX(shadowOffsetX);
        getShapeDrawableBuilder().setShadowOffsetY(shadowOffsetY);
        getShapeDrawableBuilder().setShadowSize(shadowSize);
        getShapeDrawableBuilder().intoBackground();
        setPadding(shadowSize, shadowSize, shadowSize, shadowSize);
        //由于当前view会添加到RecyclerView里，让setOnItemLongClickListener无效
        setEnabled(false);
        initView();
    }

    protected void initView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.home_top_scene_layout, this, true);
        sceneRecyclerView = view.findViewById(R.id.scene_recycler_view);
//        recycleViewIndicator = view.findViewById(R.id.recycle_view_indicator);
        btnAddScene = view.findViewById(R.id.btn_add_scene);
//        recycleViewIndicator.bindRecyclerView(sceneRecyclerView);
//        int sceneRecyclerViewWidth = DensityUtils.getScreenWidth(getContext()) - (marginLeftRight + marginLeftRight + getPaddingLeft() + getPaddingRight());
//        mHomeSceneAdapter = new HomeSceneAdapter(getContext(), sceneRecyclerViewWidth, type == 1);


        mHomeSceneAdapter = new RoomManagerSceneAdapter(getContext())
                .setSelectAct(false)
                .setShowFloorRoom(true)
                .setSingleSelect(false)
                .setBingingType(0);
        mHomeSceneAdapter.setOnChildClickListener(R.id.setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {

                SceneDetailUtil.getSceneDetailAndToEdit(((HomeActivity)getContext()), ((HomeActivity)getContext()), mHomeSceneAdapter.getData().get(position).getSceneSerialNo());
            }
        });
        mHomeSceneAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                SceneBean scene = mHomeSceneAdapter.getData().get(position);
                    if(mSceneOperateManager == null){
                        mSceneOperateManager = new SceneOperateManager(getContext());
                    }
                    mSceneOperateManager.onClick(itemView, scene.getSceneSerialNo());
            }
        });
        sceneRecyclerView.setAdapter(mHomeSceneAdapter);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
//        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        sceneRecyclerView.setLayoutManager(gridLayoutManager);
        btnAddScene.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                List<SceneBean> sceneBeans = LLSceneDBManager.getInstance(getContext()).getAll();
                if(sceneBeans.size() == 0){
                    Intent intent = new Intent(getContext(), EditSceneActivityNew.class);
                    getContext().startActivity(intent);
                }else{
                    Intent intent = new Intent(getContext(), SceneManageActivity.class);
                    getContext().startActivity(intent);
                }
            }
        });
    }

    public void refreshSceneData() {
        Observable.create(new ObservableOnSubscribe<List<SceneBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<SceneBean>> emitter) throws Exception {
                List<SceneBean> scenes = null;
                switch (type) {
                    case 0:
                        scenes = LLSceneDBManager.getInstance(getContext()).getSceneByRoom(roomSerialNo);
                        break;
                    case 1:
                        scenes = LLSceneDBManager.getInstance(getContext()).getFavouriteScenes();
                        break;
                    case 2:
                        scenes = LLSceneDBManager.getInstance(getContext()).getCommonScenes();
                        break;
                }
                emitter.onNext(scenes);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<SceneBean>>() {
                    @Override
                    public void accept(List<SceneBean> scenes) throws Exception {
                        List<SceneBean> showScene = new ArrayList<>();
                        for(int i = 0;i < scenes.size();i++){
                            if(i >= 6){
                                break;
                            }
                            showScene.add(scenes.get(i));
                        }
                        updateView(showScene);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    public void updateView(List<SceneBean> scenes) {
        StaggeredGridLayoutManager.LayoutParams sl = (StaggeredGridLayoutManager.LayoutParams) getLayoutParams();
        if (scenes != null && scenes.size() > 0) {
            btnAddScene.setVisibility(GONE);
            mHomeSceneAdapter.setData(scenes);
            sceneRecyclerView.setVisibility(View.VISIBLE);
//            if (scenes.size() <= 4) {
//                recycleViewIndicator.setVisibility(View.GONE);
//            } else {
//                recycleViewIndicator.setVisibility(View.VISIBLE);
//            }
            setPadding(shadowSize, shadowSize, shadowSize, shadowSize);
            sl.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            sl.height = StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT;
            hasScene = true;
        } else {
            if (type == 1) {//常用

                btnAddScene.setVisibility(VISIBLE);
                setPadding(shadowSize, shadowSize, shadowSize, shadowSize);
                sl.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
                sl.height = StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT;
            } else {
                sl.bottomMargin = 0;
                sl.height = 1;
                setPadding(0, 0, 0, 0);
            }
            mHomeSceneAdapter.setData(null);
            sceneRecyclerView.setVisibility(View.GONE);
//            recycleViewIndicator.setVisibility(View.GONE);
            hasScene = false;

            List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getAll();
            if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
                btnAddScene.setVisibility(GONE);
            }else{
                btnAddScene.setVisibility(devices.size() == 0 ? GONE : VISIBLE);
            }

        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (getContext() instanceof HomeActivity) {
//            boolean hasFloor = ((HomeActivity) getContext()).getHomeFragment().hasFloor();
            StaggeredGridLayoutManager.LayoutParams sl = (StaggeredGridLayoutManager.LayoutParams) getLayoutParams();
            sl.topMargin = marginTop;
//            if (hasFloor) {
//                //不是常用和通用
//                if (type != 1 && type != 2) {
//                    int topMargin = ((HomeActivity) getContext()).getHomeFragment().getSubFragmentTop();
//                    if (sl.topMargin != topMargin) {
//                        sl.topMargin = topMargin;
//                    }
//                }
//            } else {
//                sl.topMargin = marginTop;
//            }
        }
    }

    public boolean hasScene() {
        return hasScene;
    }
}
